#!/bin/bash
#!/usr/bin/env bash
set -e

export buildType="${1}"
export buildTarget="${2}"
export cangjieFolder="cangjie-${buildTarget}"

if [[ "${buildTarget}" == "android" ]]; then
    cangjieTarget="aarch64-linux-android31"
    cangjieFeatures="feature.env.android"
    export ANDROID_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/android"
    export ANDROID_NDK_DIR="${ANDROID_SDK_ROOT}/ndk/26.3.11579264"
    os_name=$(uname -s)
    if [ "$os_name" = "Linux" ]; then
        export SYSTEM_STRING="linux-x86_64"
    else
        export SYSTEM_STRING="darwin-x86_64"
    fi
    export ANDROID_CANGJIE_PATH="$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-android"
elif [[ "${buildTarget}" == "ohos" ]]; then
    cangjieTarget="aarch64-linux-ohos"
    cangjieFeatures="feature.env.ohos"
elif [[ "${buildTarget}" == "ios" ]]; then
    cangjieTarget="aarch64-apple-ios"
    cangjieFeatures="feature.env.gnu"
    export cangjieFolder="cangjie-ios"
    export IOS_SDK_DIR="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk"
    export IOS_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/ios"
    export CANGJIE_IOS_PATH="$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-ios"
elif [[ "${buildTarget}" == "ios-sim" ]]; then
    cangjieTarget="aarch64-apple-ios-simulator"
    cangjieFeatures="feature.env.gnu"
    export cangjieFolder="cangjie-ios"
    export IOS_SIM_SDK_DIR="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneSimulator.sdk"
    export IOS_SIM_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/ios-sim"
    export CANGJIE_IOS_PATH="$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-ios"
fi

if [[ "${buildType}" == "debug" ]]; then
    cangjieExtraArgs="-g"
else
    cangjieExtraArgs=""
fi

cd $(dirname $0); pwd -P
source "$CJMP_SDK_HOME/cjmp-tools/third_party/${cangjieFolder}/envsetup.sh"
cjpm build --no-feature-deduce --enable-features="${cangjieFeatures}" --target="${cangjieTarget}" ${cangjieExtraArgs}

if [[ "${buildTarget}" == "android" ]]; then
    outputDir="../android/demo/libs/arm64-v8a"
    mkdir -p "${outputDir}"
    cp "../package/target/${cangjieTarget}/${buildType}/demo/libdemo.so" "${outputDir}/"
elif [[ "${buildTarget}" == "ios" ]]; then
    frameworksDir="../ios/demo/libs"
    mkdir -p "${frameworksDir}"
    cp "../package/target/${cangjieTarget}/${buildType}/demo/libdemo.dylib" "${frameworksDir}/"
elif [[ "${buildTarget}" == "ios-sim" ]]; then
    frameworksDir="../ios/demo/libs"
    mkdir -p "${frameworksDir}"
    cp "../package/target/${cangjieTarget}/${buildType}/demo/libdemo.dylib" "${frameworksDir}/"
fi
